//
//  UIColor+kExtension.swift
//  kExtension
//
//  Created by 康凯 on 17/06/2017.
//  Copyright © 2017 康凯. All rights reserved.
//

import Foundation
import UIKit


extension UIColor {
    
    //16进制RGB
    convenience init(rgbHex rgbHexColor: String) {
        
        guard rgbHexColor.characters.count == 6 else {
            self.init(white: 0.0, alpha: 0.0)
            print("your rgbHex value was wrong, default is clearColor")
            return
        }
        
        self.init(rgbaHex: rgbHexColor + "ff")
    }
    
    // 16进制RGBA
    convenience init(rgbaHex rgbaHexColor: String){
        guard rgbaHexColor.characters.count == 8 else {
            self.init(white: 0.0, alpha: 0.0)
            print("your rgbaHex value was wrong, default is clearColor")
            return
        }
        
        // 存储转换后的数值
        var red:UInt32 = 0, green:UInt32 = 0, blue:UInt32 = 0, alpha:UInt32 = 0
        
        // 分别转换进行转换
        Scanner(string: rgbaHexColor[0..<2]).scanHexInt32(&red)
        Scanner(string: rgbaHexColor[2..<4]).scanHexInt32(&green)
        Scanner(string: rgbaHexColor[4..<6]).scanHexInt32(&blue)
        Scanner(string: rgbaHexColor[6..<8]).scanHexInt32(&alpha)
        
        self.init(red: CGFloat(red)/255.0, green: CGFloat(green)/255.0, blue: CGFloat(blue)/255.0, alpha: CGFloat(alpha)/255.0)
    }
    
    // RGB色
    convenience init(r: UInt32, g: UInt32, b: UInt32, a: Float){
        guard r < 256 && g < 256 && b < 256 && a <= 1.0 else {
            self.init(white: 0.0, alpha: 0.0)
            print("your RGBA value was wrong, default is clearColor")
            return
        }
        self.init(red: CGFloat(r)/255.0, green: CGFloat(g)/255.0, blue: CGFloat(b)/255.0, alpha: CGFloat(a))
    }
    
    // 随机颜色
    class func randomColor() -> UIColor {
        return UIColor.init(r: arc4random_uniform(255), g: arc4random_uniform(255), b: arc4random_uniform(255), a: 1)
    }
    
}


